package com.zhss.demo.register.client;

/**
 * 服务启动后调用client调用此线程将服务注册到注册中心当中
 */
public class RegisterClientWorker extends Thread{

    public static final String SERVICE_NAME = "inventory-service";
    public static final String IP = "192.168.31.207";
    public static final String HOSTNAME = "inventory01";
    public static final int PORT = 9000;


    /**
     * http通信组件
     */
    private HttpSender httpSender;

    /**
     * 是否完成服务注册
     */
    private Boolean finishedRegister;

    /**
     * 服务实例id
     */
    private String serviceInstanceId;

    public RegisterClientWorker(String serviceInstanceId) {
        this.httpSender =  new HttpSender();
        this.finishedRegister = false;
        this.serviceInstanceId = serviceInstanceId;
    }


    @Override
    public void run() {
        // 根据注册结果标识判断是否完成注册，如果没有完成注册则继续发送注册请求
        if(!finishedRegister) {
            RegisterRequest registerRequest = new RegisterRequest();
            registerRequest.setServiceName(SERVICE_NAME);
            registerRequest.setIp(IP);
            registerRequest.setHostname(HOSTNAME);
            registerRequest.setPort(PORT);
            registerRequest.setServiceInstanceId(serviceInstanceId);

            // 通过HTTP请求工具箱注册中心发送注册请求
            RegisterResponse registerResponse = httpSender.register(registerRequest);

            System.out.println("服务注册的结果是：" + registerResponse.getStatus() + "......");

            // 获取注册请求结果，请求成功更新注册标识完成注册
            if (RegisterResponse.SUCCESS.equals(registerResponse.getStatus())) {
                this.finishedRegister = true;
            } else {
                return;
            }
        }
        // 如果注册成功就行进入死循环，向注册中心发送心跳，告诉注册中心服务还在
        if (finishedRegister) {
            // 构建心跳请求
            HeartbeatRequest heartbeatRequest = new HeartbeatRequest();
            heartbeatRequest.setServiceInstanceId(serviceInstanceId);
            HeartbeatResponse heartbeatResponse = null;
            while (true) {
                try {
                    heartbeatResponse = httpSender.heartbeat(heartbeatRequest);
                    System.out.println("心跳的结果为：" + heartbeatResponse.getStatus() + "......");
                    Thread.sleep(30 * 1000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
